<?php
if ( IPB_THIS_SCRIPT != 'admin' )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'init.php'.";
	exit();
}

class ad_wages
{
	var $ipsclass;
	
	function auto_run()
	{
		$code_redirect = array(
								'list' => 'list_wages',
								'add' => 'add_wage',
								'edit' => 'edit_wage',
								'save' => 'save_wage',
								'delete' => 'delete_wage',
								'log' => 'collected_wages'
							);
		if(!$code_redirect[$this->ipsclass->input['do']])
		{
			$this->ipsclass->input['do'] = 'list';
		}
		$run = $code_redirect[$this->ipsclass->input['do']];
		$this->$run();		
	}
	
	function list_wages()
	{
		$this->ipsclass->admin->page_title  = "Welcome managing wages for ibMarket";
		$this->ipsclass->admin->page_detail = "Welcome managing wages for ibMarket. Here you can add, set, delete wages to member and groups.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;code=wages', 'Manage Wages' );
		
		$this->ipsclass->adskin->td_header[] = array( "Group"        , "" );
		$this->ipsclass->adskin->td_header[] = array( "How Much"     , "" );
		$this->ipsclass->adskin->td_header[] = array( "Next Payment" , "" );
		$this->ipsclass->adskin->td_header[] = array( "Option"       , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Group Wages");
		
		if(is_array($this->ipsclass->cache['market_wages']['group']) and count($this->ipsclass->cache['market_wages']['group']))
		{
			foreach($this->ipsclass->cache['market_wages']['group'] as $wage)
			{
				$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																					$this->ipsclass->cache['group_cache'][$wage['id_who']]['prefix'].$this->ipsclass->cache['group_cache'][$wage['id_who']]['g_title'].$this->ipsclass->cache['group_cache'][$wage['id_who']]['suffix'],
																					$this->ipsclass->numbers->format_currency($wage['how_much']),
																					$this->ipsclass->get_date($wage['next_payment'],'LONG'),
																					"<img id=\"menu_{$wage['w_id']}\" src='{$this->ipsclass->vars['board_url']}/skin_acp/IPB2_Standard/images/filebrowser_action.gif' border='0' alt='Options' class='ipd' style='float:right'/>",
																			)	);
				
				$this->ipsclass->html .= "<script type=\"text/javascript\">
	menu_build_menu( \"menu_{$wage['w_id']}\",
  new Array(
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&code=wages&do=edit&wage=".$wage['w_id']."'>Edit Wage</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&code=wages&do=delete&wage=".$wage['w_id']."'>Delete Wage</a>\"
      )     );
 </script>";
			}
		}
		else
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No group wages",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->adskin->td_header[] = array( "Member"       , "" );
		$this->ipsclass->adskin->td_header[] = array( "How Much"     , "" );
		$this->ipsclass->adskin->td_header[] = array( "Next Payment" , "" );
		$this->ipsclass->adskin->td_header[] = array( "Option"       , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Member Wages");
		
		if(is_array($this->ipsclass->cache['market_wages']['member']) and count($this->ipsclass->cache['market_wages']['member']))
		{
			$members = array();
			foreach($this->ipsclass->cache['market_wages']['member'] as $wage)
			{
				$members[$wage['id_who']] = $wage['id_who'];
				$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																					"<!--member.".$wage['id_who']."-->",
																					$this->ipsclass->numbers->format_currency($wage['how_much']),
																					$this->ipsclass->get_date($wage['next_payment'],'LONG'),
																					"<img id=\"menu_{$wage['w_id']}\" src='{$this->ipsclass->vars['board_url']}/skin_acp/IPB2_Standard/images/filebrowser_action.gif' border='0' alt='Options' class='ipd' style='float:right'/>",
																			)	);
				
				$this->ipsclass->html .= "<script type=\"text/javascript\">
	menu_build_menu( \"menu_{$wage['w_id']}\",
  new Array(
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&code=wages&do=edit&wage=".$wage['w_id']."'>Edit Wage</a>\",
			img_item   + \" <a href='{$this->ipsclass->base_url}&{$this->ipsclass->form_code_js}&code=wages&do=delete&wage=".$wage['w_id']."'>Delete Wage</a>\"
      )     );
 </script>";
			}
			$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'members','where'=>"id IN (".implode(", ",$members).")"));
			$this->ipsclass->DB->exec_query();
			while($mem = $this->ipsclass->DB->fetch_row())
			{
				$this->ipsclass->html = str_replace("<!--member.".$mem['id']."-->",$this->ipsclass->market_class->format_name($mem['id'],$mem['members_display_name'],$mem['mgroup']),$this->ipsclass->html);
				unset($members[$mem['id']]);
			}
			foreach($members as $id)
			{
				$this->ipsclass->html = str_replace("<!--member.".$id."-->","Unregistered/Deleted Member",$this->ipsclass->html);
			}
		}
		else
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic("No member wages",'center');
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->wage_form();
		
		$this->ipsclass->admin->output();
	}
	
	function wage_form($wage_id = 0)
	{
		if($wage_id)
		{
			if(!is_array($this->ipsclass->cache['market_wages']['id'][$wage_id]))
			{
				$this->ipsclass->admin->error("Cannot find the wage you are trying to edit");
			}
			if($this->ipsclass->cache['market_wages']['id'][$wage_id]['to_who'] == 'm')
			{
				$member = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'members','where'=>"id=".$this->ipsclass->cache['market_wages']['id'][$wage_id]['id_who']));
				$name = $this->ipsclass->market_class->format_name($member['id'],$member['members_display_name'],$member['mgroup']);
			}
			else
			{
				$name = $this->ipsclass->cache['group_cache'][$this->ipsclass->cache['market_wages']['id'][$wage_id]['id_who']]['prefix'].$this->ipsclass->cache['group_cache'][$this->ipsclass->cache['market_wages']['id'][$wage_id]['id_who']]['g_title'].$this->ipsclass->cache['group_cache'][$this->ipsclass->cache['market_wages']['id'][$wage_id]['id_who']]['suffix'];
			}
		}
		else
		{
			$this->ipsclass->cache['market_wages']['id'][0]['how_much'] = 0;
			$this->ipsclass->cache['market_wages']['id'][0]['w_how'] = 2;
			$this->ipsclass->cache['market_wages']['id'][0]['w_when'] = '';
			$this->ipsclass->cache['market_wages']['id'][0]['w_day'] = 0;
			$this->ipsclass->cache['market_wages']['id'][0]['w_hour'] = 0;
			$this->ipsclass->cache['market_wages']['id'][0]['w_minute'] = 0;
		}
		
		$minute = array();
		for($i = 0; $i < 60; $i++)
		{
			$minute[$i] = array($i,$i." minutes (:".sprintf("%02u",$i).")");
		}
		$minute[1] = array(1, "1 minute (:01)");
		
		$hours = array();
		for($i = 0; $i < 24; $i++)
		{
			if($i < 12)
			{
				$hours[$i] = array($i, $i." hours (".$i." AM)");
			}
			else
			{
				$hours[$i] = array($i, $i." hours (".($i - 12)." PM)");
			}
		}
		$hours[0] = array(0, "0 hours (12 AM)");
		$hours[1] = array(1, "1 hour (1 AM)");
		$hours[24] = array(24, "24 hours (Every/Any Hour)");
		
		$days = array();
		$days[0] = array(0, "0 days (Sunday)");
		$days[1] = array(1, "1 days (Monday)");
		$days[2] = array(2, "2 days (Tuesday)");
		$days[3] = array(3, "3 days (Wednesday)");
		$days[4] = array(4, "4 days (Thursday)");
		$days[5] = array(5, "5 days (Friday)");
		$days[6] = array(6, "6 days (Saturday)");
		$days[7] = array(7, "7 days (Every/Any Day)");
		
		$groups = array();
		foreach($this->ipsclass->cache['group_cache'] as $gid => $group)
		{
			$groups[] = array($gid, $group['g_title']);
		}
		
		$this->ipsclass->admin->page_title  = "Welcome to editing a wage";
		$this->ipsclass->admin->page_detail = "Welcome to editing a wage.";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;code=wages', 'Manage Wages' );
		$this->ipsclass->admin->nav[] 		= array( ''                                          , 'Edit Wage'    );
		
		if(!$wage_id)
		{
			$this->ipsclass->html .= "<div id='ipb-get-members' style='border:1px solid #000; background:#FFF; padding:2px;position:absolute;width:210px;display:none;z-index:100'></div>\n";
		}

		$this->ipsclass->html .= $this->ipsclass->adskin->start_form( array(
																	 	  	 1 => array( 'section'   , 'components'              ),
																			 2 => array( 'act'       , 'market'                  ),
																			 3 => array( 'code'      , 'wages'                   ),
																			 4 => array( 'do'        , $wage_id ? 'save' : 'add' ),
																			 5 => array( 'wage'      , $wage_id                  ),
															), 'wageform');
		
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		$this->ipsclass->adskin->td_header[] = array( "" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table($wage_id ? "Editing a wage" : "Add a wage");
		
		if($wage_id)
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>To who</b>",
																				  $name
																		 )      );
		}
		else
		{
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>Which member for this wage?</b>",
																				  $this->ipsclass->adskin->form_input("member_name",'','text',"autocomplete='off' style='width:210px' id='member_name'")
																		 )      );
	
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b><u>-OR-</u> which group for this wage</b>",
																				  $this->ipsclass->adskin->form_dropdown("group_id",$groups)
																		 )      );
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array("<b>How much?</b>",
																			  $this->ipsclass->numbers->currency_format($this->ipsclass->adskin->form_input("how_much",$this->ipsclass->cache['market_wages']['id'][$wage_id]['how_much']))
																	 )      );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_basic($this->ipsclass->adskin->form_input("info","",'text',"readonly='readonly' style='float:right; width:60%'")."How Often", 'left', 'tablesubheader');
		
		$default = "0";
		if($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_how'] == 1)
		{
			$date = $this->ipsclass->unixstamp_to_human($this->ipsclass->cache['market_wages']['id'][$wage_id]['w_when']);
			$default = sprintf("%02d/%02d/%04d %02d:%02d", $date['month'], $date['day'], $date['year'], $date['hour'] , $date['minute'] );
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>When to give the wage?</b>",
																			$this->ipsclass->adskin->form_dropdown("w_how", array(array(1,'Every so often'),array(2,'When it is this time')),$this->ipsclass->cache['market_wages']['id'][$wage_id]['w_how'], "onchange='parse_wage(this.name)'"),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>When is the last time when this is restocked?</b><br />This is in effect if and only if 'Every so often' is selected.<br />Input Format (24-hour time): MM/DD/YYYY HH:MM",
																			$this->ipsclass->adskin->form_input("w_when", $default, 'input', "onkeyup='parse_wage(this.name)'")."<input type='button' name='current_time' value='Current Time' onclick='wage_current_time()'/>",
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row(array(
																			"<b>If 'Every so often' is selected, how much time in between each wage?</b><br / ><b>If 'When it is this time' is selected, what time to give the wage?</b>",
																			$this->ipsclass->adskin->form_dropdown("w_day", $days, $this->ipsclass->cache['market_wages']['id'][$wage_id]['w_day'], "onchange='parse_wage(this.name)'")."<br />".$this->ipsclass->adskin->form_dropdown("w_hour", $hours, $this->ipsclass->cache['market_wages']['id'][$wage_id]['w_hour'], "onchange='parse_wage(this.name)'")."<br />".$this->ipsclass->adskin->form_dropdown("w_minute", $minute, $this->ipsclass->cache['market_wages']['id'][$wage_id]['w_minute'], "onchange='parse_wage(this.name)'"),
																	)	);
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_form($wage_id ? "Save wage" : "Add Wage");
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		if(!$wage_id)
		{
			$this->ipsclass->html .= "<script type=\"text/javascript\" src='{$this->ipsclass->vars['board_url']}/jscripts/ipb_xhr_findnames.js'></script>\n";
			$this->ipsclass->html .= "<script type=\"text/javascript\">\n";
			$this->ipsclass->html .= "	init_js( 'wageform', 'member_name');\n";
			$this->ipsclass->html .= "	var tmp = setTimeout( 'main_loop()', 10 );\n";
			$this->ipsclass->html .= "</script>\n";
		}
		$this->ipsclass->html .= "<script type=\"text/javascript\">\n";
		$this->ipsclass->html .= "	parse_wage('');\n";
		$this->ipsclass->html .= "</script>\n";
	}
	
	function add_wage()
	{
		if($this->ipsclass->input['wage'] != 0)
		{
			$this->ipsclass->admin->error("Invalid Action");
		}
		
		$to_who = '';
		$id_who = 0;
		$name = '';
		if($member = $this->ipsclass->DB->build_and_exec_query(array('select'=>'*','from'=>'members','where'=>"members_l_display_name='".strtolower($this->ipsclass->input['member_name'])."'")))
		{
			$to_who = 'm';
			$id_who = $member['id'];
			$name = $member['members_display_name'];
		}
		else
		{
			$to_who = 'g';
			$id_who = $this->ipsclass->input['group_id'];
			$name = $this->ipsclass->cache['group_cache'][$this->ipsclass->input['group_id']]['g_title'];
		}
		
		$this->ipsclass->cache['market_wages']['id'][0]['to_who'] = $to_who;
		$this->ipsclass->cache['market_wages']['id'][0]['id_who'] = $id_who;
		
		$this->parse_input();
		
		$this->ipsclass->DB->do_insert('market_wages',$this->ipsclass->cache['market_wages']['id'][0]);
		
		$this->ipsclass->market_class->cache_wages();
		
		$this->ipsclass->admin->save_log("ibMarket: Add wage to ".$name);
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=wages","Wage added...");
	}
	
	function parse_input()
	{
		if(!$this->ipsclass->input['how_much'])
		{
			$this->ipsclass->admin->error("You need to specify a non-zero amount");
		}
		
		$this->ipsclass->input['w_how'] = intval($this->ipsclass->input['w_how']);
		if($this->ipsclass->input['w_how'] == 1)
		{
			list($date, $time) = explode(" ",$this->ipsclass->input['w_when']);
			list($month,$day,$year) = explode("/",$date);
			list($hour,$minute) = explode(":",$time);
			if($this->ipsclass->market_class->check_24_time($month, $day, $year, $hour, $minute))
			{
				$this->ipsclass->input['w_when'] = $this->ipsclass->convert_local_date_to_unix( array(  'month'  => intval($month),
																										'day'    => intval($day),
																										'year'   => intval($year),
																										'hour'   => intval($hour),
																										'minute' => intval($minute) ) );
			}
			else
			{
				$this->ipsclass->input['w_when'] = time();
				$this->ipsclass->input['w_when'] = $this->ipsclass->input['w_when'] - $this->ipsclass->input['w_when'] % 60;
			}
		}
		else
		{
			$this->ipsclass->input['w_when'] = 0;
		}
		
		$this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['how_much'] = $this->ipsclass->numbers->parse_input_number($this->ipsclass->input['how_much'],'int');
		$this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['w_how'] = $this->ipsclass->input['w_how'];
		$this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['w_when'] = $this->ipsclass->input['w_when'];
		$this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['w_day'] = $this->ipsclass->input['w_day'];
		$this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['w_hour'] = $this->ipsclass->input['w_hour'];
		$this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['w_minute'] = $this->ipsclass->input['w_minute'];
		$this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['next_payment'] = $this->ipsclass->market_class->next_wage_time($this->ipsclass->input['wage']);
	}
	
	function edit_wage()
	{
		$this->wage_form(intval($this->ipsclass->input['wage']));

		$this->ipsclass->admin->output();
	}
	
	function save_wage()
	{
		$this->ipsclass->input['wage'] = intval($this->ipsclass->input['wage']);
		if(!is_array($this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]))
		{
			$this->ipsclass->admin->error("Cannot find the wage you are trying to edit");
		}
		
		$this->parse_input();
		
		$this->ipsclass->DB->do_update('market_wages',array(
																'how_much' => $this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['how_much'],
																'next_payment' => $this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['next_payment'],
																'w_how' => $this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['w_how'],
																'w_when' => $this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['w_when'],
																'w_day' => $this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['w_day'],
																'w_hour' => $this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['w_hour'],
																'w_minute' => $this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]['w_minute'],
					),"w_id=".$this->ipsclass->input['wage']);
		
		$this->ipsclass->market_class->cache_wages();
		
		$this->ipsclass->admin->save_log("ibMarket: Editted wage");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=wages","Wage edited and saved...");
	}
	
	function delete_wage()
	{
		$this->ipsclass->input['wage'] = intval($this->ipsclass->input['wage']);
		if(!is_array($this->ipsclass->cache['market_wages']['id'][$this->ipsclass->input['wage']]))
		{
			$this->ipsclass->admin->error("Cannot find the wage you are trying to delete");
		}
		
		$this->ipsclass->DB->build_and_exec_query(array('delete'=>'market_wages','where'=>"w_id=".$this->ipsclass->input['wage']));
		
		$this->ipsclass->market_class->cache_wages();
		
		$this->ipsclass->admin->save_log("ibMarket: Deleted wage");
		
		$this->ipsclass->admin->redirect($this->ipsclass->form_code_js."&code=wages","Wage deleted...");
	}
	
	function collected_wages()
	{
		$LIMIT = 50;
		$this->ipsclass->input['st'] = intval($this->ipsclass->input['st']);
		
		$this->ipsclass->admin->page_title  = "Welcome to collected wages page for the Bank";
		$this->ipsclass->admin->page_detail = "Welcome to collected wages page for the Bank";
		$this->ipsclass->admin->nav[] 		= array( $this->ipsclass->form_code.'&amp;code=wages&amp;do=log', 'Collected Wages' );
		
		$total = $this->ipsclass->DB->build_and_exec_query(array('select'=>'COUNT(*) as total','from'=>'market_wages_collected'));
		$page = $this->ipsclass->adskin->build_pagelinks(	array(	'TOTAL_POSS'   => $total['total'],
																	'PER_PAGE'     => $LIMIT,
																	'USE_ST'       => 'st',
																	'CUR_ST_VAL'   => $this->ipsclass->input['st'],
																	'L_SINGLE'     => "Single Page",
																	'BASE_URL'     => $this->ipsclass->base_url."&amp;".$this->ipsclass->form_code."&amp;code=wages&amp;do=log"
															)	);

		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->html .= "<br />";
		
		$this->ipsclass->adskin->td_header[] = array( "Who"    , "" );
		$this->ipsclass->adskin->td_header[] = array( "When"   , "" );
		$this->ipsclass->adskin->td_header[] = array( "Amount" , "" );
		
		$this->ipsclass->html .= $this->ipsclass->adskin->start_table("Collected Wages");
		
		$collected = array();
		$members = array();
		$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'market_wages_collected','order'=>'time_collected DESC','limit'=>array($this->ipsclass->input['st'],$LIMIT)));
		$this->ipsclass->DB->exec_query();
		while($collect = $this->ipsclass->DB->fetch_row())
		{
			$collected[$collect['c_id']] = $collect;
			if($collect['to_who'] == 'm')
			{
				$members[$collect['id_who']] = "ID: ".$collect['id_who'];
			}
		}
		
		if(count($members))
		{
			$this->ipsclass->DB->build_query(array('select'=>'*','from'=>'members','where'=>"id IN (".implode(", ",array_keys($members)).")"));
			$this->ipsclass->DB->exec_query();
			while($member = $this->ipsclass->DB->fetch_row())
			{
				$members[$member['id']] = $member['members_display_name'];
			}
		}
		
		foreach($collected as $collect)
		{
			if($collect['to_who'] == 'm')
			{
				$name = $members[$collect['id_who']];
			}
			else
			{
				$name = $this->ipsclass->cache['group_cache'][$collect['id_who']]['prefix'].$this->ipsclass->cache['group_cache'][$collect['id_who']]['g_title'].$this->ipsclass->cache['group_cache'][$collect['id_who']]['suffix'];
			}
			$this->ipsclass->html .= $this->ipsclass->adskin->add_td_row( array(  $name,
																				  $this->ipsclass->get_date($collect['time_collected'],'LONG'),
																				  $this->ipsclass->numbers->format_currency($collect['how_much'])
																		 )      );
		}
		
		$this->ipsclass->html .= $this->ipsclass->adskin->end_table();
		
		$this->ipsclass->html .= $this->ipsclass->adskin->add_standalone_row($page,"left");
		
		$this->ipsclass->admin->output();
	}
}
?>